﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web.Security;
using System.Threading;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using System.IO;
using HIS.Utils;
using HISModels.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.Text.RegularExpressions;

namespace HIS.Controllers.FrontOffice {
    public class Registration : HIS.Controllers.AppBaseController {
        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private StringReader stringReader = null;
        private PatientReg oPatientRegistration = null;
        private Patient oPatient = null;
        private Doctor oDoctor = null;
        private DocRegRefRel oDocRegRefRel = null;
        string strJson = string.Empty;
        private string appointdkrpt = string.Empty;
        private string doctordkrpt = string.Empty;

        #endregion

        public Registration() {

        }

        [Authorization(RoleAction = "fo-registration")]
        public override void Index() {
            string Lob = HttpContext.Current.Session["Lob"].ToString();
            if (string.IsNullOrEmpty(Lob) && ConfigurationManager.AppSettings["usinglob"]=="true") {
                //flag
                string url = Data["rooturl"] + "frontoffice/lobselection/?redirectUri=frontoffice/registration";
                HttpContext.Current.Response.Redirect(url);
            }
            try {
                Data.Add("Pagetitle", "Patient Data Registration");
                Data.Add("Lob", Lob.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString().ToUpper());
                Data.Add("Actionform", Data["rooturl"] + "frontoffice/registration/");
                Data.Add("Notification", strNotification);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                RenderFile("FrontOffice\\searchpatient.html");
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void RegistrationNextStep() {
            try {
                Data.Add("Pagetitle", "Registration");
                string Lob = HttpContext.Current.Session["Lob"].NullSafeToString();
                Data.Add("Lob", Lob.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString().ToUpper());
                Data.Add("Notification", string.Empty);
                oPatient = new Patient(); Utils.Helper.SetNullToEmptyString(oPatient);
                oPatientRegistration = new PatientReg(); Utils.Helper.SetNullToEmptyString(oPatientRegistration);
                oPatient = (Patient)HttpContext.Current.Session["oPatient"];

                //Gender
                if (oPatient.GenderId == 1) {
                    Data.Add("Gender", "Male");
                } else if (oPatient.GenderId == 2) {
                    Data.Add("Gender", "Female");
                } else { Data.Add("Gender", string.Empty); }

                if (oPatient.Birthdate.ToString("dd/MM/yyyy") == "01/01/0001") {
                    Data.Add("Age", string.Empty);
                } else {
                    Data.Add("Age", Utils.Helper.GetAge(oPatient.Birthdate));
                }
                
                Data.Add("oPatient", oPatient);


                appointdkrpt = HttpContext.Current.Session["appointdkrpt"].NullSafeToString();
                doctordkrpt = HttpContext.Current.Session["doctordkrpt"].NullSafeToString();
                if (!string.IsNullOrEmpty(appointdkrpt)) {
                    string[] str = appointdkrpt.Split(';');
                    Data.Add("doctorId",str[6].NullSafeToString());
                    Data.Add("doctorName", str[2].NullSafeToString());
                    Data.Add("UserId", str[3].NullSafeToString());
                } else if (!string.IsNullOrEmpty(doctordkrpt)) {
                    string[] str = doctordkrpt.Split(';');
                    Data.Add("doctorId", str[0].NullSafeToString());
                    Data.Add("doctorName", str[1].NullSafeToString());
                    Data.Add("UserId", str[2].NullSafeToString());
                } else {
                    Data.Add("doctorId", string.Empty);
                    Data.Add("doctorName", string.Empty);
                    Data.Add("UserId", string.Empty);
                } 
                
                RenderFile("FrontOffice\\registrationnextstep.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void RegistrationNextStepPost() {
            string returnValue = string.Empty;
            string sEcho = string.Empty;
            try {
                oDoctor = new Doctor(); Utils.Helper.SetNullToEmptyString(oDoctor);
                oPatient = new Patient(); Utils.Helper.SetNullToEmptyString(oPatient);
                oDocRegRefRel = new DocRegRefRel(); Utils.Helper.SetNullToEmptyString(oDocRegRefRel);
                DoctorRegRel oDoctorRegRelation = new DoctorRegRel(); Utils.Helper.SetNullToEmptyString(oDoctorRegRelation);
                DocRegRefRel oDoctorRegRefRel = new DocRegRefRel(); Utils.Helper.SetNullToEmptyString(oDoctorRegRefRel);
                oPatientRegistration = new PatientReg(); Utils.Helper.SetNullToEmptyString(oPatientRegistration);

                oPatient = (Patient)HttpContext.Current.Session["oPatient"];

                string isSubmit = Convert.ToString(HttpContext.Current.Request["HiddenIsSubmit"]);
                if (isSubmit == "1") {
                    sEcho = HttpContext.Current.Request["sEcho"];
                    #region Doctor
                    //Handler Doctor
                    string doctorId =Convert.ToString(HttpContext.Current.Request["HiddenDoctorIdValue"]);
                    oDoctor.Id = doctorId != string.Empty ? Convert.ToInt32(doctorId) : 0;
                    string HiddenUserId = Convert.ToString(HttpContext.Current.Request["HiddenUserId"]);
                    string doctorName = Convert.ToString(HttpContext.Current.Session["doctorName"]);

                    HttpContext.Current.Session.Remove("doctordkrpt");
                    HttpContext.Current.Session.Remove("appointdkrpt");
                    
                    //Refering Doctor
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request["HiddenReferedDoctorIdValue"])) {
                        oDocRegRefRel.DoctorId = Convert.ToInt32(HttpContext.Current.Request["HiddenReferedDoctorIdValue"]);
                        oDocRegRefRel.IsExtDoctor = 0;
                        oPatientRegistration.DocRegRefRels.Add(oDocRegRefRel);
                    }
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request["HiddenReferedExtDoctorIdValue"])) {
                        oDocRegRefRel.DoctorExtId = Convert.ToInt32(HttpContext.Current.Request["HiddenReferedExtDoctorIdValue"]);
                        oDocRegRefRel.IsExtDoctor = 1;
                        oPatientRegistration.DocRegRefRels.Add(oDocRegRefRel);
                    }

                    //Add Doctor Reg Rel
                    oDoctorRegRelation.DoctorId = oDoctor.Id;
                    oPatientRegistration.DoctorRegRels.Add(oDoctorRegRelation);
                    #endregion doctor

                    //Add patientRegistration
                    oPatientRegistration.PatientId = oPatient.Id;
                    oPatientRegistration.HuLobRelId = Convert.ToInt32(HttpContext.Current.Session["Lob"]);

                    string strUri = Global.ServiceUriDictionary["registration"] + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(oPatientRegistration));
                    oPatientRegistration = JsonConvert.DeserializeObject<PatientReg>(stringReader.ReadToEnd());

                    if (oPatientRegistration != null) {
                        strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        string lobId = oPatientRegistration.HuLobRelId.ToString();

                        string huCode = base.RestService.ObjectResponse.Headers["huCode"].ToString();
                        string lobCode = oPatientRegistration.HuLobRelId.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString();
                        string strPush = lobId + "&" + oPatient.Id + "&" + oDoctor.Id + "&" + oPatientRegistration.RegistrationTime.NullSafeToString() + "&" + huCode + "&" + lobCode;
                        HIS.Push.ChanelInstance.Instance.SendToSpesificDoctor(strPush, HiddenUserId);

                    } else {
                        strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                    }
                }


                #region doctorregpaging
                
                sEcho = HttpContext.Current.Request["sEcho"];
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = "patientid=" + oPatient.Id.ToString();

                string Uri = Global.ServiceUriDictionary["doctorregpaging"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.PostJson(Uri, JsonConvert.SerializeObject(pagingSearch));


                JObject Jobj = JObject.Parse(stringReader.ReadToEnd());
                JArray aaData = (JArray)Jobj["aaData"];
                JArray aaDataModified = new JArray();

                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    DateTime tempDate = (DateTime)oo["RegistrationTime"];
                    oo["RegistrationTime"] = tempDate.ToString(HISModels.Enums.StaticVariables.DateTimeFormat);
                    JArray arIntDoc = (JArray)oo["DoctorIntRefName"];
                    JArray arExtDoc = (JArray)oo["DoctorExtRefName"];
                    if (arIntDoc.Count!=0) {
                        oo["ReferingDoctor"] = oo["DoctorIntRefName"][0]["DocName"];
                    } else if (arExtDoc.Count!=0) {
                        oo["ReferingDoctor"] = oo["DoctorExtRefName"][0]["DocName"];
                    }
                    else {
                        oo["ReferingDoctor"] = string.Empty;
                    }
                    aaDataModified.Add(oo);
                }

                Jobj["aaData"] = aaDataModified;

                if (Jobj["iTotalDisplayRecords"].ToString() == "0") {
                    strJson = "{\"sEcho\":" + sEcho + ",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"aaData\":[]}";
                } else {
                    strJson = JsonConvert.SerializeObject(Jobj);
                }

                #endregion

            } catch (Exception ex) {
                strJson = "{\"sEcho\":\"" + sEcho + "\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"ExceptionMessage\":\"Exception Occured : "+ex.Message+"\",\"aaData\":[]}";
            } finally {
                HttpContext.Current.Response.Write(strJson);
            }


        }

        [Authorization(RoleAction = "fo-registration")]
        public void SearchDoctor() {
            try {
                HttpContext.Current.Session.Remove("appointdkrpt");
                HttpContext.Current.Session.Remove("doctordkrpt");

                string ddlSpecialist = Utils.Helper.DropDownSpecialist("TextBoxDoctorSpecialist", "",false, base.RestService);
                Data.Add("ddlSpecialists", ddlSpecialist);
                Data.Add("Pagetitle", "Doctor List");
                string Lob = HttpContext.Current.Session["Lob"].NullSafeToString();
                Data.Add("Lob", Lob.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString().ToUpper());
                Data.Add("Notification", strNotification);
                RenderFile("FrontOffice\\registrationdoctorlist.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        
        [Authorization(RoleAction = "fo-registration")]
        public void SearchAppointment() {
            try {
                HttpContext.Current.Session.Remove("appointdkrpt");
                HttpContext.Current.Session.Remove("doctordkrpt");

                Data.Add("Pagetitle", "Appointment List");
                string Lob = HttpContext.Current.Session["Lob"].NullSafeToString();
                Data.Add("Lob", Lob.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString().ToUpper());
                //Data.Add("Lob", Lob);
                string ddlSpecialist = Utils.Helper.DropDownSpecialist("DoctorSpecialistId", "",false, base.RestService);
                Data.Add("ddlSpecialists", ddlSpecialist);
                Data.Add("Notification", strNotification);
                RenderFile("FrontOffice\\registrationappointmentlist.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void TableListAppointment() {
            string strJson = string.Empty;
            string sEcho = HttpContext.Current.Request["sEcho"];
            try {
                string TextBoxBookerName = HttpContext.Current.Request["TextBoxBookerName"].NullSafeToString();
                string TextBoxDoctorName = HttpContext.Current.Request["TextBoxDoctorName"].NullSafeToString();
                string DoctorSpecialistId = HttpContext.Current.Request["DoctorSpecialistId"].NullSafeToString();
                string ssearch = "TextBoxBookerName=" + TextBoxBookerName + ";TextBoxDoctorName=" + TextBoxDoctorName + ";DoctorSpecialistId=" + DoctorSpecialistId;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = Global.ServiceUriDictionary["appregpaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));

                ///Convert to JObject
                try {
                    JObject o = JObject.Parse(stringReader.ReadToEnd());
                    JArray aaData = (JArray)o["aaData"];

                    ///Modify it
                    JArray aaDataModified = new JArray();

                    for (int i = 0; i < aaData.Count(); i++) {
                        JObject oo = JObject.Parse(aaData[i].ToString());
                        DateTime startTime = (DateTime)oo["StartTime"];
                        oo["StartTime"] = startTime.ToString("hh:mm");
                        DateTime endTime = (DateTime)oo["EndTime"];
                        oo["EndTime"] = endTime.ToString("hh:mm");
                        oo["appointenkrp"] = KeanuMvc.Reference.CryptoString.Encrypt((oo["AppointmentId"] + ";" +
                                             oo["BookerName"] + ";" + oo["DoctorName"] + ";" +
                                             oo["UserId"] + ";" + oo["Address"] + ";" + 
                                             oo["PhoneNumber"]+";"+oo["DoctorId"]).ToString());
                        aaDataModified.Add(oo);
                    }
                    o["aaData"] = aaDataModified;
                    strJson = JsonConvert.SerializeObject(o);
                } catch {
                    strJson = "{\"sEcho\":2,\"iTotalRecords\":22,\"iTotalDisplayRecords\":22,\"aaData\":[]}";
                }

                stringReader.Dispose();
                base.RestService.Dispose();
            } catch (Exception ex) {
                strJson = "{\"sEcho\":\"" + sEcho + "\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"ExceptionMessage\":\"Exception Occured : " + ex.Message + "\",\"aaData\":[]}";
            } finally {
                HttpContext.Current.Response.Write(strJson);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void RegistrationList() {
            try {
                Data.Add("Pagetitle", "Registration List");
                string Lob = HttpContext.Current.Session["Lob"].NullSafeToString();
                Data.Add("Lob", Lob.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString().ToUpper());
                Data.Add("Actionform", Data["rooturl"] + "frontoffice/registrationlist/");
                Data.Add("Notification", strNotification);
                RenderFile("FrontOffice\\registrationlist.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void TableListRegistration() {
            try {
                try {
                    HttpContext.Current.Session.Remove("oPatientRegistration");
                    HttpContext.Current.Session.Remove("oPatient");
                } catch {

                }

                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];

                string regno = HttpContext.Current.Request["regno"].NullSafeToString();
                string patientname = HttpContext.Current.Request["patientname"].NullSafeToString();
                string doctorname = HttpContext.Current.Request["doctorname"].NullSafeToString();
                string regdate = HttpContext.Current.Request["regdate"].NullSafeToString();
                if (!string.IsNullOrEmpty(regdate)) {
                    Match match = Regex.Match(regdate, @"^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$", RegexOptions.IgnoreCase);
                    if (!match.Success) {
                        regdate = "01/01/0001";
                    }
                }      
                string ssearch = "regno=" + regno + ";patientname=" + patientname + ";doctorname=" + doctorname+";regdate=" + regdate;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = Global.ServiceUriDictionary["regpaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));

                ///Convert to JObject
                try {
                    JObject o = JObject.Parse(stringReader.ReadToEnd());
                    JArray aaData = (JArray)o["aaData"];

                    ///Modify it
                    JArray aaDataModified = new JArray();

                    for (int i = 0; i < aaData.Count(); i++) {
                        JObject oo = JObject.Parse(aaData[i].ToString());
                        //DateTime tempDate = (DateTime)oo["RegDate"];
                        //oo["RegDate"] = tempDate.ToShortIndonesian(false);
                        aaDataModified.Add(oo);
                    }
                    o["aaData"] = aaDataModified;
                    ///So serialize
                    strJson = JsonConvert.SerializeObject(o);
                } catch {
                    strJson = "{\"sEcho\":2,\"iTotalRecords\":22,\"iTotalDisplayRecords\":22,\"aaData\":[]}";
                }
                
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void GetClock() {
            string thistime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); //Javascript Date Format
            HttpContext.Current.Response.Write(thistime);
        }

        [Authorization(RoleAction = "fo-registration")]
        public void UploadHandler() {
            HttpFileCollection files = HttpContext.Current.Request.Files;
            foreach (string fileTagName in files) {
                HttpPostedFile file = HttpContext.Current.Request.Files[fileTagName];
                if (file.ContentLength > 0) {
                    int size = file.ContentLength;
                    string name = file.FileName;
                    int position = name.LastIndexOf("\\");
                    name = name.Substring(position + 1);
                    string contentType = file.ContentType;
                    byte[] fileData = new byte[size];
                    file.InputStream.Read(fileData, 0, size);

                }
            }

            UploadHandler oFileUploadHandler = new UploadHandler();
            try {
                string patientIdCard = HttpContext.Current.Request["IdentityCardbNumber"];
                oFileUploadHandler.ProcessRequest(HttpContext.Current);
                string result = "{\"strNotification\": \"ok\"}";
                HttpContext.Current.Response.Write(result);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void AddExternalDoctor() {
            try {
                Data.Add("Pagetitle", "Add New External Doctor");
                Data.Add("DdDoctorSalutation", Utils.Helper.GetDoctorSalutation("TitleBeforeName", string.Empty).NullSafeToString());
                Data.Add("DdDoctorTitle", Utils.Helper.GetDoctorTitle("TitleAfterName", string.Empty).NullSafeToString());
                string ddlSpecialist = Utils.Helper.GetDocSpecialistVal("Specialist", "","class='required'", true, base.RestService);
                Data.Add("ddlSpecialists", ddlSpecialist);

                Data.Add("Notification", strNotification);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                RenderFile("FrontOffice\\registrationaddnewextdoctor.html");
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void AddExternalDoctorPost() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try {
                DoctorExt oDoctorExt = new DoctorExt();
                Address oDoctorExtAddress = new Address();
                oDoctorExt.PostHandler<DoctorExt>();
                oDoctorExtAddress.PostHandler<Address>();
                oDoctorExtAddress.TypeId = 1;

                oDoctorExt.Addresses.Add(oDoctorExtAddress);
                strUri = Global.ServiceUriDictionary["doctorexternal"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(oDoctorExt));
                try {
                    oDoctorExt = JsonConvert.DeserializeObject<DoctorExt>(stringReader.ReadToEnd());
                } catch { }
                if (oDoctorExt != null) {
                    strNotification = "{\"strNotification\": \"1\",\"DoctorId\": \"" + oDoctorExt.Id + "\",\"TitleBeforeName\": \"" + oDoctorExt.TitleBeforeName + "\",\"TitleAfterName\": \"" + oDoctorExt.TitleAfterName + "\",\"DoctorName\": \"" + oDoctorExt.FullName + "\"}";
                } else { 
                    strNotification = base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString();
                    strNotification = "{\"strNotification\": \"" + strNotification + "\"}"; 
                }

                
            } catch (Exception ex) {
                strNotification = "{\"strNotification\": \"" + ex.Message + "\"}"; 
            } finally {
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }

    }
}